/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package listgen.controller;

import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class DatabaseController {
    
    public DatabaseController() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException
    {
            Class.forName( "org.postgresql.Driver" ).newInstance();
            
            url = "jdbc:postgresql://localhost:5432/songDB" ;
            
            connection = DriverManager.getConnection(url, "watermelon" , "hello");
//            statement = connection.createStatement();
//            statement.execute("insert into users values('b','b')");
   }
    
    public boolean checkInfo(String id, String password) throws SQLException, NoSuchAlgorithmException
    {
        String  sql = "select password from users where id = \'";   
        sql += id + "\'";
        statement = connection.prepareStatement(
                "SELECT password FROM users WHERE id = ?");
        statement.setString(1, id);
        statement.executeQuery();
        
        resultSet = statement.executeQuery();
                
        if (resultSet.next())
        {
                java.security.MessageDigest md;
                md = java.security.MessageDigest.getInstance("MD5");
                md.update(password.getBytes());
                byte[] byteDigest = md.digest();
                    String md5Str = "";  

            for (int i = 0; i < byteDigest.length; i++) {  
                if (Integer.toHexString(0xFF & byteDigest[i]).length() == 1) {  
                    md5Str += "0";
                    md5Str += Integer.toHexString(0xFF & byteDigest[i]);
                } else  {
                    md5Str += Integer.toHexString(0xFF & byteDigest[i]);  
                }  
                
            } 
//            System.out.println(resultSet.getString(1));
//            System.out.println(md5Str);
            return md5Str.equals(resultSet.getString(1));
        }
        return false;
    }
    
    private Connection connection;
    private String url;
    private PreparedStatement statement;
    private ResultSet resultSet;
}
